﻿using MediatR;
using SheepCultivation.Common.Domain;
using SheepCultivation.Common.Dto;
using SheepCultivation.Common.Infrastructure.Interface;
using SheepCultivation.Enum;
using System.Security.Cryptography;

namespace SheepCultivation.API.AddliCation.EnterPriseW
{
    public class EnterPriseTreeSeachHandler : IRequestHandler<EnterPriseTreeSeachCommon, Result>
    {
        public readonly IBaseRepository<EnterPriseTree> EnterPriseTreeRepository;

        public EnterPriseTreeSeachHandler(IBaseRepository<EnterPriseTree> enterPriseTreeRepository)
        {
            EnterPriseTreeRepository = enterPriseTreeRepository;
        }

        public async Task<Result> Handle(EnterPriseTreeSeachCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.error };
            try
            {
                result.Code = (int)CommonEnumCode.success;
                var list = EnterPriseTreeRepository.GetAll().Where(x => x.Pid == 0).ToList();
                List<TreeDto> data = new List<TreeDto>();
                foreach (var item in list)
                {
                    TreeDto TreeDto1 = new TreeDto();
                    TreeDto1.value = item.EnterPriseTreeId;
                    TreeDto1.label = item.unitName;
                    TreeDto1.children = new List<TreeDto>();
                    var list2 = EnterPriseTreeRepository.GetAll().Where(x => x.Pid == item.EnterPriseTreeId).ToList();
                    foreach (var item2 in list2)
                    {
                        TreeDto TreeDto2 = new TreeDto();
                        TreeDto2.value = item2.EnterPriseTreeId;
                        TreeDto2.label = item2.unitName;
                        TreeDto2.children = new List<TreeDto>();
                        TreeDto1.children.Add(TreeDto2);
                        var list3 = EnterPriseTreeRepository.GetAll().Where(x => x.Pid == item2.EnterPriseTreeId).ToList();
                        foreach (var item3 in list3)
                        {
                            TreeDto TreeDto3 = new TreeDto();
                            TreeDto3.value = item3.EnterPriseTreeId;
                            TreeDto3.label = item3.unitName;
                            TreeDto3.children = new List<TreeDto>();
                            TreeDto1.children.Add(TreeDto3);
                        }
                    }
                    data.Add(TreeDto1);
                }
                result.Data = data;
                result.Msg = "企业树形显示";
            }
            catch (Exception ex)
            {

            }
            return result;
        }

    }
    public class TreeDto
    {
        public int value { get; set; }
        public string label { get; set; }
        public List<TreeDto> children { get; set; }
    }

}
